package ApplicationStart.Configuration;

import ApplicationStart.Domain.ReaderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


/**
 * 注入到WebSecurity
 */
@EnableWebSecurity //去匹配web security 配置 -- configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{

    private final ReaderRepository readerRepository;

    @Autowired
    public WebSecurityConfiguration(ReaderRepository readerRepository) {
        this.readerRepository = readerRepository;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").access("hasRole('READER')")
                .antMatchers("/**").permitAll()
                .and().formLogin()
                .loginPage("/login")
                .failureForwardUrl("/login?error=true")
                .and().logout().logoutUrl("/logout");
    }

    //认证的时候会触发这个
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(readerRepository::findByUserName);
    }
}
